package com.huida.app.streamusage;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;


/**
 * @author wangzhuangzhuang
 * @DESC:
 * @date 2022-02-14 17:26
 */
@SpringBootTest
@Slf4j
public class StreamUsageTestUnit02 {

	@Test
	public void test01(){
		// reduce初始值为0，累加器可以是Lambda表达式也可以是方法引用
		List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

		int res01 = numbers
				.stream().reduce(0, (subtotal, element) -> (subtotal + element));
		log.info("result: {}", res01); // result: 21

		int res02 = numbers
				.stream().reduce(0, Integer::sum);
		log.info("result: {}", res02); // result: 21
	}

	@Test
	public void test02(){
		// 不仅可以归约Integer类型，只要累加器参数类型能够匹配可以对任何类型的集合进行规约计算
		List<String> letters = Arrays.asList("a", "b", "c", "d", "e");
		String res01 = letters
				.stream()
				.reduce("", (partialString, element) -> partialString + element);
		log.info("res01: {}", res01); // res01: abcde

		String res02 = letters
				.stream()
				.reduce("", String::concat);
		log.info("res02: {}", res02); // res02: abcde
	}


	@Test
	public void test03(){
		Employee e1 = new Employee(1,23,"M","Rick","Beethovan");
		Employee e2 = new Employee(2,13,"F","Martina","Hengis");
		Employee e3 = new Employee(3,43,"M","Ricky","Martin");
		Employee e4 = new Employee(4,26,"M","Jon","Lowman");
		Employee e5 = new Employee(5,19,"F","Cristine","Maria");
		Employee e6 = new Employee(6,15,"M","David","Feezor");
		Employee e7 = new Employee(7,68,"F","Melissa","Roy");
		Employee e8 = new Employee(8,79,"M","Alex","Gussin");
		Employee e9 = new Employee(9,15,"F","Neetu","Singh");
		Employee e10 = new Employee(10,45,"M","Naveen","Jain");

		List<Employee> employees = Arrays.asList(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10);

		Integer total = employees.stream().map(Employee::getAge).reduce(0, Integer::sum);
		log.info("total: {}", total); // total: 346
	}
	/**
	 * 先用map将Stream流中的元素由Employee类型处理为Integer类型（age）。
	 * 然后对Stream流中的Integer类型进行归约
	 * */

	@Test
	public void test04(){
		Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion")
				.parallel()
				.forEach(System.out::println);

		Stream.of("Monkey", "Lion", "Giraffe", "Lemur", "Lion")
				.parallel()
				.forEachOrdered(System.out::println);

/*		Giraffe
		Lemur
		Monkey
		Lion
		Lion
		// ====
		Monkey
		Lion
		Giraffe
		Lemur
		Lion*/
	}

}